/**
 * 购物车
 */
var CartHeader = React.createClass({
    handleDelClick: function(e){
        var $list = $(".goodlist .icon-select.cur");
        if($list.length == 0){
            this.props.showMsg('请选择要删除的商品');
        }else{
            this.props.showDialog('确定删除选中商品？');
        }
        e.stopPropagation();
        e.preventDefault();
    },
    render: function() {
        return (
            <header data-am-widget="header" className="am-header am-header-default am-header-fixed am-no-layout">
                <h1 className="am-header-title">进货车</h1>
                <div className="am-header-right am-header-nav am-dropdown" id="am-dropdown">
                    <a onClick={this.handleDelClick}><i className="icon_topdelete"></i></a>
                </div>
            </header>
        )
    }
});
//商品列表
var GoodsItem = React.createClass({
    handleModifyClick: function(e){
        $('#my-popup').modal('open');
        this.props.modifyCartPopup(this.props.offerId);
        e.stopPropagation();
        e.preventDefault();
    },
    handleSelectClick: function(e){
        var target = e.target, cName = $.trim(target.className);
        if(cName.indexOf('cur') >= 0){
            //减
            target.className = cName.replace(/cur/g, '');
        }else {
            //加
            target.className = cName + ' cur';
        }
        this.props.setTotal();
        e.stopPropagation();
        e.preventDefault();
    },
    render: function() {
        var totalCount = 0, specsArr = [], totalPrice = 0;
        this.props.specs.forEach(function(value){
            specsArr.push(
                <div data-color={value.color} data-color-desc={value.colorDesc} data-length={value.length} data-length-desc={value.lengthDesc} data-number={value.number}>
                    {value.colorDesc}，{value.lengthDesc}码，{value.number}双；
                </div>
            );
            totalCount += parseInt(value.number);
        });
        totalPrice = totalCount * parseFloat(this.props.price);
        return (
            <div className="item am-margin-bottom-sm am-padding-left-sm am-padding-right-sm bg-white">
                <div className="box prelative padding-left-25px am-padding-top-sm am-padding-bottom-sm border-bottom font-14">
                    <div className="box-1 am-text-truncate am-padding-right-sm"></div>
                    <div className="font-color-main" onClick={this.handleModifyClick}> 修改</div>
                </div>
                <div className="goodlist">
                    <div className="gooditem border-bottom box am-padding-top-sm am-padding-bottom-sm prelative">
                        <div className="width-35px"><i onClick={this.handleSelectClick} data-count={totalCount} data-price={totalPrice} data-id={this.props.offerId} className="icon-select"></i></div>
                        <div>
                            <img src={IMG_PRE+this.props.img} className="width-100px"/>
                        </div>
                        <div className="box-1 am-margin-left-sm am-margin-top-xs">
                            <div className="box">
                                <div className="box-1 am-text-truncate">{this.props.name}</div>
                                <div className="font-color-1 font-14">x{totalCount}</div>
                            </div>
                            <div className="box font-14 font-color-1">
                                <div>已选:</div>
                                <div className="box-1 specs" data-id={this.props.offerId} data-name={this.props.name} data-price={totalPrice} data-img={this.props.img}>{specsArr}</div>
                            </div>
                            <div className="font-color-main">&yen;{parseFloat(totalPrice).toFixed(2)}</div>
                        </div>
                    </div>
                </div>
            </div>
        )
    }
});

var CartPrice = React.createClass({
    handleSubmitClick:function(){
        var $list = $(".goodlist .icon-select.cur").parent().parent();
        if($list.length > 0){
            $list = $list.find('.specs');
            var param = {
                //userId: USER.userId,
                price: this.props.total.price,
                offers: []
            };
            for(var i = 0, l = $list.length; i < l; i ++){
                var spec = $list[i], offer = {
                    id: spec.getAttribute('data-id'),
                    name: spec.getAttribute('data-name'),
                    price: spec.getAttribute('data-price'),
                    img: spec.getAttribute('data-img'),
                    specs: []
                };
                var s = spec.querySelectorAll('div');
                for(var j = 0, ll = s.length; j < ll; j++){
                    var spec = {
                        color: s[j].getAttribute('data-color'),
                        colorDesc: s[j].getAttribute('data-color-desc'),
                        length: s[j].getAttribute('data-length'),
                        lengthDesc: s[j].getAttribute('data-length-desc'),
                        number: s[j].getAttribute('data-number'),
                    };
                    offer.specs.push(spec);
                }
                param.offers.push(offer);
            }
            this.props.submitItems(param);
        }
    },
    handleSelectClick:function(e){
        var target = e.target, cName = $.trim(target.className);
        if(cName.indexOf('cur') >= 0){
            target.className = cName.replace(/cur/g, '');
            $(".goodlist .icon-select").removeClass("cur");
        }else{
            target.className = cName + ' cur';
            $(".goodlist .icon-select").addClass("cur");
        }
        this.props.setTotal();
        e.stopPropagation();
        e.preventDefault();
    },
    render:function() {
        var styleObj = {
            'position':'fixed',
            'bottom':'49px',
            'left': '0px',
            'width': '100%',
            'background-color':'#fff'
        };
        return (
            <div className="box border-tops" style={styleObj}>
                <div className="box box-1 am-padding-bottom-xs am-padding-top-xs ">
                    <div className="font-color-2 prelative am-padding-top-ss am-padding-left-lg am-margin-left-sm">
                        <i onClick={this.handleSelectClick} className="bottomselect icon-select"></i> 全选
                    </div>
                    <div className="box-1 am-text-right am-padding-top-ss">
                        <div>合计：<span className="font-color-main">&yen;{parseFloat(this.props.total.price).toFixed(2)}</span></div>
                    </div>
                    <div className="font-12 am-margin-left-sm font-color-1">
                        <div>共{this.props.total.count}件</div>
                        <div>不含运费</div>
                    </div>
                </div>
                <div onClick={this.handleSubmitClick} className="bg-2 am-margin-left-sm line-51 width-80px am-text-center font-color-white">提交</div>
            </div>
        )
    }
});

//商品列表
var CartMain = React.createClass({
    getInitialState: function() {
        return ({
            isTipShow: true
        })
    },
    handleRedirectClick: function() {
       location.href = 'yfsm.html';
    },
    handleCloseClick: function() {
        this.setState({
            isTipShow: false
        })
    },
    render: function() {
        var tipStyleObj = {},itemsArr = [];
        if(!this.state.isTipShow){
            tipStyleObj = {
                'display': 'none'
            }
        }
        this.props.items.forEach(function(value){
            itemsArr.push(<GoodsItem setTotal={this.props.setTotal} modifyCartPopup={this.props.modifyCartPopup} specs={value.specs} price={value.price} img={value.imgURL} name={value.offerName} offerId={value.offerId}/>);
        }.bind(this));
        return (
            <section id="amz-main" data-tag="css-nav">
                <div style={tipStyleObj} className="bg-gray am-padding-left-lg am-padding-bottom-xs am-padding-top-xs font-14 font-color-1 prelative">
                    <i className="icon-xxi"></i>
                    <div><a onClick={this.handleRedirectClick}>［运费不会算？点我告诉你！］</a></div>
                    <i onClick={this.handleCloseClick} className="icon-qx" style={tipStyleObj}></i>
                </div>
                <div className="padding-bottom-55">{itemsArr}</div>
                <CartPrice submitItems={this.props.submitItems} setTotal={this.props.setTotal} total={this.props.total} />
            </section>
        )
    }
});

var ChooseItem = function (props) {
    return (
        <div className="box am-padding-top-ss am-padding-bottom-ss border-bottom">
            <div className="am-padding-left-sm width-100px">{props.color}</div>
            <div className="am-padding-left-sm width-100px">{props.length}</div>
            <div className="box-1">
                <div className="box">
                    <div className="goodjian am-margin-right-sm"></div>
                    <div className="goodnum" data-id={props.cId + '-' + props.sId}>{props.num}</div>
                    <div className="goodjia am-margin-left-sm am-margin-right-sm"></div>
                </div>
            </div>
        </div>
    )
};
//购物车修改面板
var CartPopup = React.createClass({
    getInitialState: function(){
        return {
            curIndex: 0,
            specs: Immutable.Map({})
        }
    },
    componentWillReceiveProps: function (nextProps) {
        //已经选择的商品
        var specsMap = this.state.specs;
        nextProps.choose.forEach(function(value){
            var count = parseInt(value.item_number);
            if(count > 0){
                specsMap = specsMap.update(value.color_id+'-'+value.length_id, function(){return value.item_number;})
            }
        });
        this.setState({
            specs: specsMap
        });
    },
    handleAddClick: function(e){
        $('#my-popup').modal('close');
        var cartSpecs = [];
        this.state.specs.map(function(value, key){
            cartSpecs.push({
                'color': key.split('-')[0],
                'length': key.split('-')[1],
                'number': value
            })
        });
        this.props.updateCart({
            specs: cartSpecs
        });
        e.stopPropagation();
        e.preventDefault();
    },
    handleChangeClick: function(e){
        var target = e.target;
        if(target.nodeName === 'A'){
            var id = parseInt(target.getAttribute('data-index')),
                value = target.getAttribute('data-value');
            this.setState({
                curIndex: id
            })
        }
        e.stopPropagation();
        e.preventDefault();
    },
    handleGoodNumClick: function(e) {
        var target = e.target,num = null;
        if(target.className.indexOf('goodjian') >= 0){
            //减少
            num = target.nextElementSibling;
            var count = parseInt(num.innerHTML);
            if(count > 0) {
                num.innerHTML = --count;
                if(count === 0){
                    //数量减为0 删除该商品
                    this.setState({
                        specs: this.state.specs.delete(num.getAttribute('data-id'))
                    });
                }else{
                    //update 数量
                    this.setState({
                        specs: this.state.specs.update(num.getAttribute('data-id'), function(){return count;})
                    });
                }
            }
        }else if(target.className.indexOf('goodjia') >= 0){
            //添加
            num = target.previousElementSibling;
            var count = parseInt(num.innerHTML);
            num.innerHTML = ++count;
            this.setState({
                specs: this.state.specs.update(num.getAttribute('data-id'), function(){return count;})
            });
        }
        e.stopPropagation();
        e.preventDefault();
    },
    render: function(){
        var styleObj = {'height': '75%', 'top': '25%', 'bottom': '0'},
            styleObj2 = {'position': 'absolute', 'width': '100%', 'bottom': '0', 'padding-top': '0px', 'padding-bottom': '49px'};
        var colorsArr = [], itemsArr = [], selectedArr = [],
            l = this.props.colors.length, l2 = this.props.lengths.length,
            curTotal = 0;
        //选择框颜色、鞋码
        for(var i = 0; i < l ; i++){
            var cId = this.props.colors[i].id, color = this.props.colors[i].spec_value;
            colorsArr.push(<li><a className={i == this.state.curIndex ? 'cur': ''} data-index={i} data-value={color}>{color}</a></li>);

            for(var j = 0; j < l2; j++){
                var sId = this.props.lengths[j].id,
                    size = this.props.lengths[j].spec_value,
                    count = this.state.specs.get(cId + '-' + sId);
                //已选的颜色、鞋码
                if(count && (count = parseInt(count)) > 0){
                    selectedArr.push(<div>{color}，{size}码，{count}双;</div>);
                }else {
                    count = 0;
                }
                curTotal += count;

                if(i == this.state.curIndex) {
                    itemsArr.push(<ChooseItem cId={cId} color={color} sId={sId} length={size} num={count}/>);
                }
            }
        }
        return (
            <div className="am-popup" id="my-popup" style={styleObj}>
                <div className="am-popup-inner" style={styleObj2}>
                    <i className="icon-guanbi" data-am-modal-close style={{'top': '10px'}}></i>
                    <div className="am-popup-bd am-padding-left-0 am-padding-right-0">
                        <div className="am-padding-left-sm am-padding-right-sm">
                            <div className="box">
                                <div className="width-100px prelative" style={{'background-color': '#fff'}}>
                                    <img className="width-100px border-radius-5" src={IMG_PRE+this.props.img}/>
                                </div>
                                <div className="box-1 am-margin-top-sm am-margin-left-sm am-padding-top-sm">
                                    <div className="font-color-monney">&yen;{parseFloat(this.props.price).toFixed(2)}</div>
                                    <div className="am-text-truncate font-color-2">{this.props.name}</div>
                                </div>
                            </div>
                            <div className="box am-padding-sm border-tops am-margin-top-sm am-padding-left-0  am-cf am-padding-bottom-0">
                                <div className="font-color-2 padding-top-1">已选</div>
                                <div className="font-color-1 box-1 am-margin-left-sm">
                                    <div className="resou">
                                        <ul onClick={this.handleChangeClick}>{colorsArr}</ul>
                                    </div>
                                </div>
                            </div>
                        </div>
                        <div className="bg-white font-color-1" onClick={this.handleGoodNumClick}>
                            <div className="box am-padding-top-ss am-padding-bottom-ss bg-gray">
                                <div className="am-padding-left-sm width-100px">颜色</div>
                                <div className="am-padding-left-sm width-100px">码数</div>
                                <div className="box-1">购买数量</div>
                            </div>
                            {itemsArr}
                        </div>
                        <div className="box am-padding-sm">
                            <div className="font-color-2">已选</div>
                            <div className="font-color-1 box-1 am-margin-left-sm" >{selectedArr}</div>
                        </div>
                    </div>
                </div>
                <footer data-am-widget="navbar" className="am-navbar am-cf am-navbar-default">
                    <ul className="am-navbar-nav am-cf am-avg-sm-4 am-padding-right-0">
                        <li>
                            <a className="am-text-left">
                                <span className="font-color-monney">&yen;{parseFloat(this.props.price * curTotal).toFixed(2)} </span>
                                <span className="font-14 font-color-2"> 共{curTotal}件</span>
                            </a>
                        </li>
                        <li>
                            <a onClick={this.handleAddClick} className="bg-2 font-color-white font-15 line-51">确定</a>
                        </li>
                    </ul>
                </footer>
            </div>
        )
    }
});
var CartFooter = React.createClass({
    render: function(){
        return (
            <footer className="am-navbar am-cf am-navbar-default">
                <ul className="am-navbar-nav am-cf am-avg-sm-4">
                    <li><a href="index.html"><img src={"../assets/images/icons/home.png"} alt="首页" /><span className="am-navbar-label">首页</span></a></li>
                    <li><a href="#"><img src="../assets/images/icons/service.png" alt="客服" /><span className="am-navbar-label">客服</span></a></li>
                    <li><a href="cart.html" className='selected'><img src={"../assets/images/icons/ShoppingCart_on.png"} alt="进货车" /><span className="am-navbar-label">进货车</span></a></li>
                    <li><a href="personal.html"><img src={"../assets/images/icons/my.png"} alt="我的" /><span className="am-navbar-label">我的</span></a></li>
                </ul>
            </footer>
        )
    }
});
var Page = React.createClass({
    getInitialState: function() {
        return {
            dialogHidden: true,
            dialogMsg: '',
            msgHidden: true,
            msg: '',
            items: [],
            totalPrice: 0,
            totalCount: 0,
            modifyId: '',
            name: '',
            colors: [],
            lengths: [],
            choose: [],
            price: '',
            img: ''
        }
    },
    getCartItems: function(){
        if(ifUser()){
            $.ajax(
                getAjaxOps('/cart/qryCartItems', {
                    userId: USER.userId
                })
            ).done(function (res) {
                    if(res.resultCode == 0){
                        if(res.data && res.data.items){
                            this.setState({
                                items: res.data.items
                            });
                            this.setTotal();
                        }
                    }
                }.bind(this));
        }
    },
    componentDidMount: function(){
        this.getCartItems();
    },
    showMsg: function(msg){
        this.setState({
            msgHidden: false,
            msg: msg
        });
    },
    closeMsg: function(){
        this.setState({
            msgHidden: true
        });
    },
    showDialog: function(msg){
        this.setState({
            dialogHidden: false,
            dialogMsg: msg
        });
    },
    closeDialog: function(){
        this.setState({
            dialogHidden: true
        });
    },
    submitItems: function(param){
        /*$.ajax(
            getAjaxOps('/order/commitFromCart', param)
        ).done(function (res) {
                if(res.resultCode == 0){
                }else {
                    this.setState({
                        msgHidden: false,
                        msg: res.resultMsg
                    });
                }
            });*/
        localStorage.setItem('order', JSON.stringify(param));
        location.href = 'confirm.html';
    },
    deleteItems: function() {
        var $list = $(".goodlist .icon-select.cur"), idArr = [];
        for(var i = 0 , l = $list.length; i < l ; i ++){
            idArr.push($list[i].getAttribute('data-id'));
        }
        var param = {
            userId: USER.userId,
            ids: idArr.join(',')
        };
        $.ajax(
            getAjaxOps('/cart/delItems', param)
        ).done(function (res) {
            if(res.resultCode == 0){
                this.showMsg('删除成功');
                location.reload();
            }else{
                this.showMsg(res.resultMsg);
            }
        }.bind(this));
    },
    modifyCartPopup: function(id){
        $.ajax(
            getAjaxOps('/cart/qryOfferInCart', {
                    userId: USER.userId,
                    offerId: id
                })
        ).done(function (res) {
                if(res.resultCode == 0){
                    this.setState({
                        modifyId: id,
                        name: res.data.offer_name,
                        price: res.data.price,
                        img: res.data.imgUrl,
                        colors: res.data.offerColors,
                        lengths: res.data.offerLengths,
                        choose: res.data.choose
                    });
                }
            }.bind(this));
    },
    updateCart: function(data){
        //修改某个商品购买信息
        if(ifUser()){
            data.userId = USER.userId;
            data.offerId = this.state.modifyId;
            $.ajax(
                getAjaxOps('/cart/updateItem',{"itemStr":JSON.stringify(data)})
            ).done(function (res) {
                    if(res.resultCode == 0){
                        //刷新购物车
                        this.getCartItems();
                    }else{
                        this.setState({
                            msgHidden: false,
                            msg: res.resultMsg
                        });
                    }
                }.bind(this));
        }
    },
    setTotal: function(){
        var $list = $(".goodlist .icon-select.cur"), price = 0, count = 0;
        for(var i = 0, l = $list.length; i < l ; i ++){
            var item = $list[i];
            price += parseFloat(item.getAttribute('data-price'));
            count += parseFloat(item.getAttribute('data-count'));
        }
        this.setState({
            totalPrice: price,
            totalCount: count
        })
    },
    render: function() {
        return (
            <div>
                <CartHeader title={'一手鞋'} showMsg={this.showMsg} showDialog={this.showDialog} />
                <CartMain submitItems={this.submitItems} setTotal={this.setTotal} total={{'price': this.state.totalPrice,'count':this.state.totalCount}} items={this.state.items} modifyCartPopup={this.modifyCartPopup}/>
                <CartFooter />
                <CartPopup price={this.state.price} colors={this.state.colors} lengths={this.state.lengths} img={this.state.img}
                           offerId={this.state.modifyId} choose={this.state.choose}  updateCart={this.updateCart}/>
                <Dialog hidden={this.state.dialogHidden} msg={this.state.dialogMsg} on={this.deleteItems} close={this.closeDialog}/>
                <Message hidden={this.state.msgHidden} msg={this.state.msg} url={this.state.msgUrl} close={this.closeMsg}/>
            </div>
        )
    }

});

ReactDOM.render(
    <Page />,
    document.getElementById('root')
);

